<template>
  <div class="app-container">
    <div v-if="crud.props.searchToggle">
      <el-input v-model="query.name" clearable size="small" placeholder="输入名称搜索" style="width: 200px;"
                class="filter-item" @keyup.enter.native="crud.toQuery"/>
      <rrOperation/>
    </div>
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <template slot="right">
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            @click="pictureManagement(crud.selections[0])"
            :disabled="crud.selections.length !== 1"
          >
            图片管理
          </el-button>
        </template>
      </crudOperation>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="企业性质" prop="nature">
            <el-select v-model="form.nature" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.company_nature"
                :key="item.id"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="区代码" prop="areaCode">
            <div class="block">
              <el-cascader
                :props="{value:'code',label:'areaName',children:'childrenList' }"
                v-model="form.areaCode"
                :options="options"
                @change="handleChange"></el-cascader>
            </div>
          </el-form-item>

          <el-form-item label="供应医院">
            <el-select v-model="form.hpIds" multiple placeholder="请选择">
              <el-option
                collapse-tags
                v-for="item in hospitals"
                :key="item.id"
                :label="item.mnName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称(蒙)" prop="mnName">
            <el-input v-model="form.mnName" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="名称(汉)" prop="zhName">
            <el-input v-model="form.zhName" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="所在地(蒙)" >
            <el-input v-model="form.mnLocation" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="所在地(汉)">
            <el-input v-model="form.zhLocation" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="联系方式" prop="contactInformation">
            <el-input v-model="form.contactInformation" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="法人(蒙)" prop="mnLegalPerson">
            <el-input v-model="form.mnLegalPerson" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="法人(汉)" prop="zhLegalPerson">
            <el-input v-model="form.zhLegalPerson" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="研发药物(蒙)" >
            <el-input v-model="form.mnMedicine" :rows="3" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="研发药物(汉)" >
            <el-input v-model="form.zhMedicine" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="业务方向(蒙)" >
            <el-input v-model="form.mnDirection" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="业务方向(汉)" >
            <el-input v-model="form.zhDirection" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="面积" prop="floorSpace">
            <el-input v-model="form.floorSpace" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="面积单位" prop="floorSpaceUnit">
            <el-select v-model="form.floorSpaceUnit" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.floor_space_unit"
                :key="item.id"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="简介(蒙)" >
            <el-input v-model="form.mnIntro" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="简介(汉)" >
            <el-input v-model="form.zhIntro" type="textarea" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="id"/>
        <el-table-column prop="nature" label="企业性质">
          <template slot-scope="scope">
            {{ dict.label.company_nature[scope.row.nature] }}
          </template>
        </el-table-column>
        <el-table-column prop="areaCode" label="区代码"/>
        <el-table-column prop="image" label="照片" align="center">
          <template slot-scope="scope">
            <el-image
              :src="baseApi + '/file' +scope.row.image"
              :preview-src-list="[baseApi + '/file' + scope.row.image]"
              fit="fit"
              lazy
            >
              <div slot="error">
                <i class="el-icon-document"/>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="mnName" label="名称(蒙)"/>
        <el-table-column prop="zhName" label="名称(汉)"/>
        <el-table-column prop="zhLocation" label="坐在地(汉)"/>
        <el-table-column prop="contactInformation" label="联系方式"/>
        <el-table-column prop="zhLegalPerson" label="法人(汉)"/>
        <el-table-column prop="floorSpace" label="面积"/>
        <el-table-column prop="floorSpaceUnit" label="面积单位">
          <template slot-scope="scope">
            {{ dict.label.floor_space_unit[scope.row.floorSpaceUnit] }}
          </template>
        </el-table-column>
        <el-table-column prop="zhIntro" label="简介(汉)"/>
        <el-table-column prop="createBy" label="创建者"/>
        <el-table-column prop="updateBy" label="修改者"/>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeState(scope.row,scope.row.status)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','pharmaceuticalCompany:edit','pharmaceuticalCompany:del'])" label="操作"
                         width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
            <el-button size="mini" type="success" icon="el-icon-upload2" @click="submit(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>


      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <el-upload
          multiple
          :limit="10"
          class="file-box"
          ref="upload"
          action="/upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :on-exceed="handleExceed"
          :file-list="images"
          list-type="picture"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>

          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitFile()">上传到服务器
          </el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <el-row :gutter="20">
          <el-col v-for="url in imageurls" :span="6">
            <el-image
              style="width: 100px; height: 100px"
              :src="url"
              fit="fill"></el-image>
          </el-col>
        </el-row>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import crudPharmaceuticalCompany from '@/api/pharmaceuticalCompany'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import {getAreaTreeList} from "@/api/province/area";
import {getToken} from "@/utils/auth";
import {mapGetters} from "vuex";
import {uploadImages} from "@/api/pharmaceuticalCompany";
import {getNameAndId} from "@/api/medicine/hospital";


const defaultForm = {
  id: null,
  nature: null,
  areaCode: null,
  hpIds: null,
  mnName: null,
  mnNameCode: null,
  zhName: null,
  mnLocation: null,
  mnLocationCode: null,
  zhLocation: null,
  contactInformation: null,
  mnLegalPerson: null,
  mnLegalPersonCode: null,
  zhLegalPerson: null,
  mnMedicine: null,
  mnMedicineCode: null,
  zhMedicine: null,
  mnDirection: null,
  mnDirectionCode: null,
  zhDirection: null,
  floorSpace: null,
  floorSpaceUnit: null,
  mnIntro: null,
  mnIntroCode: null,
  zhIntro: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  status: null,
  remark: null
}
export default {
  name: 'PharmaceuticalCompany',
  components: {pagination, crudOperation, rrOperation, udOperation},
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['company_nature', 'floor_space_unit'],
  cruds() {
    return CRUD({
      title: '药企管理',
      url: 'api/pharmaceuticalCompany',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: {...crudPharmaceuticalCompany}
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'pharmaceuticalCompany:add'],
        edit: ['admin', 'pharmaceuticalCompany:edit'],
        del: ['admin', 'pharmaceuticalCompany:del']
      },
      companyId: '',
      images: [],
      imageurls: [],
      input: '',
      rules: {
        nature: [
          {required: true, message: '请选择企业性质', trigger: 'change'}
        ],
        areaCode: [
          {required: true, message: '请选择区代码', trigger: 'change'}
        ],
        mnName: [
          {required: true, message: '请输入名称(蒙)', trigger: 'change'}
        ],
        zhName: [
          {required: true, message: '请输入名称(汉)', trigger: 'change'}
        ],
        mnLocation: [
          {required: true, message: '请输入所在地(蒙)', trigger: 'change'}
        ],
        zhLocation: [
          {required: true, message: '请输入坐在地(汉)', trigger: 'change'}
        ],
        contactInformation: [
          {required: true, message: '请输入联系方式', trigger: 'change'}
        ],
        mnLegalPerson: [
          {required: true, message: '请输入法人(蒙)', trigger: 'change'}
        ],
        zhLegalPerson: [
          {required: true, message: '请输入法人(汉)', trigger: 'change'}
        ],
        mnMedicine: [
          {required: true, message: '请输入研发药物(蒙)', trigger: 'change'}
        ],
        zhMedicine: [
          {required: true, message: '请输入研发药物(汉)', trigger: 'change'}
        ],
        mnDirection: [
          {required: true, message: '请输入业务方向(蒙)', trigger: 'change'}
        ],
        zhDirection: [
          {required: true, message: '请输入业务方向(汉)', trigger: 'change'}
        ],
        floorSpace: [
          {required: true, message: '请输入占地面积', trigger: 'change'}
        ],
        floorSpaceUnit: [
          {required: true, message: '请选择面积单位', trigger: 'change'}
        ],
        mnIntro: [
          {required: true, message: '请输入简介(蒙)', trigger: 'change'}
        ],
        zhIntro: [
          {required: true, message: '请输入简介(汉)', trigger: 'change'}
        ]
      },
      options: [],
      value: {},
      dialogVisible: false,
      action: null,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      hospitals: []

    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    handleChange(val) {
      this.form.areaCode = val[val.length - 1];
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    pictureManagement(row) {
      this.$router.push({path: '/medicine/companyPicture', query: {param: row.id}})
    },
    changeState(data, val) {
      this.$confirm('此操作将修改状态值为 ' + val + ' 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudPharmaceuticalCompany.edit(data).then(res => {
          this.$message({
            type: 'waring',
            message: '修改成功'
          });
        });
      }).catch(() => {
        if (val === 1) {
          data.status = 0;
        } else {
          data.status = 1;
        }
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
      });
    },
    submit(row) {
      this.companyId = row.id;
      this.dialogVisible = true;
      // this.action = "/api/pharmaceuticalCompany/uploadProcessDefinition/" + row.id
    },
    handleAvatarSuccess() {
      location.reload();
    },
    search() {
      getByName(encodeURIComponent(this.input)).then(res => {
        this.crud.data = res;
      })
    },
    handleRemove(file, fileList) {
      this.images = fileList
      console.log("移除文件列表时的钩子", file);
    },
    //点击某个文件时的钩子
    handlePreview(file) {
      console.log("点击某个文件时的钩子", file);
    },
    //添加到上传列表时的钩子
    handleChange(file, fileList) {
      this.images = fileList
      console.log("添加到上传列表时的钩子", file)
    },
    //文件超出个数限制时的钩子
    handleExceed() {
      this.$message.warning("文件超出10个")
      console.log("文件超出个数限制时的钩子")
    },
    getImages() {
      this.$axios.get("/filelist")
        .then(response => {
          this.imageurls = response.data
          console.log("获取图片列表成功")
        })
        .catch(error => {
          this.$message.error("获取图片列表失败")
        })
    },
    submitFile() {
      if (this.images.length === 0) {
        this.$message.warning("请选择文件")
        return
      }
      const formData = new FormData();
      this.images.forEach(file => {
        formData.append("images", file.raw) //将文件传到表单中，files属性是后端接受的参数名
      })
      formData.append("companyId", this.companyId)
      uploadImages(formData).then(res => {
        this.$message({
          type: 'success',
          message: '图片上传成功!'
        })
        this.images = []
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '图片上传失败!'
        })
      })
    },
  },
  mounted() {
    getAreaTreeList().then(res => {
      this.options = res;
    }),
      getNameAndId().then(res => {
        this.hospitals = res;
      })
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi',
      'imagesUploadApi'
    ])
  }

}
</script>

<style scoped>

</style>
